<template>
	<div>
		<div class="search">
			<input 
				v-model="keyword"
				type="text" 
				placeholder="输入城市名或拼音"
				class="search-input"/>
		</div>
		<div class="search-content" ref="search" v-show="keyword">
			<ul>
				<li 
					v-for="item of list" 
					class="search-item border-bottom"
					:key="item.id"
					@click="handleCityClick(item.name)"
				>
					{{item.name}}
				</li>
				<li 
					v-show="hasNoData" 
					class="search-item border-bottom"
				>
					没有找到匹配数据
				</li>
			</ul>
		</div>
	</div>
</template>

<script>
import BScroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: "CitySearch",
  props: {
  	cities: Object
  },
  data () {
  	return {
  		keyword: '',
  		list: [],
  		timer: null
  	}
  },
  computed: {
  	hasNoData () {
  		return !this.list.length
  	}
  },
  watch: {
  	keyword () {
  		if (this.timer) {
  			clearTimeout(this.timer)
  		}
  		//如果 this.keyword 为空，那么就让 this.list 变为空数组并返回
  		if (!this.keyword) {
  			this.list = []
  			return
  		}
  		this.timer = setTimeout(() => {
  			const result = []
  			//通过for...in...循环 cities 中的每一项
  			for (let i in this.cities) {
  				//cities 中的每一项都是一个数组，因此可以使用 forEach 遍历
  				this.cities[i].forEach((value) => {
  					//indexOf()用于检索字符串首次出现的位置，不存在则返回-1
  					if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
  						result.push(value)
  					}
  				})
  			}
  			//将数组 result 加入 list 当中
  			this.list = result
  		},100)
  	}
  },
  methods: {
  	handleCityClick (city) {
		this.changeCity(city)
		this.$router.push('/')
	},
	...mapMutations(['changeCity'])
  },
  mounted () {
  	this.scroll = new BScroll(this.$refs.search,{click:true})
  }
}
</script>

<style lang="stylus" scoped>
  @import "../../../assets/styles/varibles.styl"
  .search
    height: .32rem
    background: $bgColor
    padding: 0 .12rem .06rem .12rem
    .search-input
      box-sizing: border-box
      width: 100%
      height: .32rem
      line-height: .24rem
      padding: 0 .04rem
      text-align: center
      border-radius: .04rem
      color: #666
  .search-content
    position: absolute
    top: 0.74rem
    left: 0
    right: 0
    bottom: 0
    background-color: #eee
    z-index: 1
    overflow: hidden
    .search-item
    	line-height: .32rem
    	padding-left: .12rem
    	background: #fff
    	color: #666
</style>
